package gold.digger;

import gold.vo.ListNode;

import java.util.LinkedList;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC445 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            LinkedList<Integer> linkedList1 = new LinkedList<>();
            LinkedList<Integer> linkedList2 = new LinkedList<>();
            LinkedList<Integer> sumList = new LinkedList<>();
            while (l1 != null) {
                linkedList1.addFirst(l1.val);
                l1 = l1.next;
            }
            while (l2 != null) {
                linkedList2.addFirst(l2.val);
                l2 = l2.next;
            }

            //swap
            if (linkedList1.size() < linkedList2.size()) {
                LinkedList<Integer> temp = linkedList1;
                linkedList1 = linkedList2;
                linkedList2 = temp;
            }

            int lastStep = 0, curSum = 0;
            while (!linkedList2.isEmpty()) {
                curSum = linkedList1.pollFirst() + linkedList2.pollFirst() + lastStep;
                lastStep = curSum / 10;
                curSum %= 10;
                sumList.addFirst(curSum);
            }
            while (!linkedList1.isEmpty()) {
                curSum = linkedList1.pollFirst() + lastStep;
                lastStep = curSum / 10;
                curSum %= 10;
                sumList.addFirst(curSum);
            }

            if (lastStep > 0) sumList.addFirst(lastStep);

            ListNode res = new ListNode(sumList.pollFirst()), cur = res;
            while (!sumList.isEmpty()) {
                cur.next = new ListNode(sumList.pollFirst());
                cur = cur.next;
            }

            return res;
        }
    }

    public void run() {
        Solution solution = new Solution();
        ListNode l1 = ListNode.createList("5");
        ListNode l2 = ListNode.createList("5");
        System.out.println(solution.addTwoNumbers(l1, l2));
    }

    public static void main(String[] args) throws Exception {
        LC445 an = new LC445();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
